package UDPEchoServerAndSlient;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Description: 简单的基于UDP的回显服务器
 * User:岁亮亮
 * Date:2025-04-05
 * TIME:19:59
 */
public class UDPEchoSlient {

    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UDPEchoSlient(String serverIP,int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客服端启动 ->");
        Scanner scanner = new Scanner(System.in);
        while(true){
            //客户端 是 有要发送的请求就构造并发送到服务器 没有就进入阻塞状态
            //1.从控制器上读取请求
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //2.构造请求并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length
                                                             , InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //3.进入等待 若服务器返回响应 并读取
            DatagramPacket resposePacket = new DatagramPacket(new byte[4040],4040);
            socket.receive(resposePacket);
            //4.返回响应到控制器上
            String response = new String(resposePacket.getData(),0,resposePacket.getLength());
            System.out.printf("响应 : %s",response);
            System.out.println();
        }
    }
    public static void main(String[] args) throws IOException {
        UDPEchoSlient slient = new UDPEchoSlient("127.0.0.1",9090);
        slient.start();
    }
}
